package com.argrace.smart.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.entity.ZigBeeDeviceDetailEntity;
import com.argrace.smart.entity.ZigBeeDeviceEntity;
import com.argrace.smart.ui.DrawableSwitch;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;
import com.zhouyou.view.seekbar.SignSeekBar;

import java.util.HashMap;

/**
 * Created by argrace_dev_1 on 2018/2/1.
 */

public class MyDeviceControlActivity extends BaseActivity {
    private MineZigBeeDeviceListEntity bean;
    private DrawableSwitch drawableswitch;
    private TextView send;
    private TextView tv_log;
    private SignSeekBar seekBar;
    BroadcastReceiver receiver;
    Handler handler = new Handler();
    private EditText et_key, et_value;
    private int num = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mydevicecontrol);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        setView();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i("info", "control收到推送" + intent.getExtras().getString("msg"));
                Log.i("info", "control收到下推测试" + intent.getExtras().getString("text"));
                JSONObject obj = JSON.parseObject(intent.getExtras().getString("msg"));
                toastActBtm("control收到下推" + intent.getExtras().getString("msg"));

                getDeviceDetailInfo();
                String state = obj.getString("text");
//                if (state != null && state.equals("0")) {
//
//
//
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            drawableswitch.setSwitchOn(false);
//                            drawableswitch.invalidate();
//                        }
//                    });
//
//                }
//                if (state != null && state.equals("1")) {
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            drawableswitch.setSwitchOn(true);
//                            drawableswitch.invalidate();
//                        }
//                    });
//
//                }
            }
        };
        IntentFilter filter = new IntentFilter("com.example.broadcast");
        registerReceiver(receiver, filter);
        getDeviceDetailInfo();
    }

    private void setView() {
        drawableswitch = (DrawableSwitch) findViewById(R.id.activity_mydevicecontrol_switch);
        send = (TextView) findViewById(R.id.activity_mydevicecontrol_send);
        et_key = (EditText) findViewById(R.id.activity_mydevicecontrol_et_key);
        et_value = (EditText) findViewById(R.id.activity_mydevicecontrol_et_value);
        tv_log = (TextView) findViewById(R.id.activity_mydevicecontrol_tv_log);
        seekBar = (SignSeekBar) findViewById(R.id.activity_mydevicecontrol_seekbar);
        seekBar.setOnProgressChangedListener(new SignSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(SignSeekBar signSeekBar, int progress, float progressFloat, boolean fromUser) {
                Logg.i("info","onProgressChanged,progress=" +progress + "---progressFloat=" + progressFloat );
            }

            @Override
            public void getProgressOnActionUp(SignSeekBar signSeekBar, int progress, float progressFloat) {
                Logg.i("info","getProgressOnActionUp,progress=" +progress + "---progressFloat=" + progressFloat );
            }

            @Override
            public void getProgressOnFinally(SignSeekBar signSeekBar, int progress, float progressFloat, boolean fromUser) {
                Logg.i("info","getProgressOnFinally,progress=" +progress + "---progressFloat=" + progressFloat );
            }
        });

        drawableswitch.setListener(new DrawableSwitch.MySwitchStateChangeListener() {
            @Override
            public void mySwitchStateChanged(boolean isSwitchOn) {
                sendMsg();
            }
        });
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_key.getText() == null || et_value.getText() == null) {
                    toastActBtm("请输入参数");
                    return;
                }
                String key = et_key.getText().toString();
                String value = et_value.getText().toString();
                sendMsg(key, value);
            }
        });
    }

    private void sendMsg() {
        String method = "mtop.openalink.app.core.device.set.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        int state = drawableswitch.isSwitchOn() ? 1 : 0;
        params.put("setParams", "{\"Switch_1\":\"" + state + "\"}");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "发送消息成功" + transitoryResponse.data);
                getDeviceDetailInfo();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "发送消息失败");
            }
        });


    }

    private void sendMsg(String key, String value) {
        String method = "mtop.openalink.app.core.device.set.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        params.put("setParams", "{\"" + key + "\":\"" + value + "\"}");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "发送消息成功" + transitoryResponse.data);
                getDeviceDetailInfo();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "发送消息失败");
            }
        });
    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    Log.i("info", "子设备最新状态成功，数据为空，不操作");
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);

                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                tv_log.setText("第 " + num + "次响应：" + transitoryResponse.data.toString());
                num++;
                Key_ValueEntity bean = JSON.parseObject(obj.getString("Switch_1"), Key_ValueEntity.class);
                //0关闭，1开启
                if (bean.getValue().equals("0")) {
                    drawableswitch.setSwitchOn(false);
                } else {
                    drawableswitch.setSwitchOn(true);
                }
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
